// pages/order/order.js
const app = getApp()
import mode from '../../utils/mode.js'
import Dialog from '../../miniprogram_npm/@vant/weapp/dialog/dialog.js'
Page({
  options: {
    pureDataPattern: /^_/
  },
  /**
   * 页面的初始数据
   */
  data: {
    active: 0,
    iscancel: false,
    reasonForCancellation: '',
    cancelId: '',
    reasonList: [],
    _active: [
      { cancel: '取消订单', confirm: '立即付款' },
      { cancel: '查看物流', confirm: '确认收货' },
      { cancel: '取消订单', confirm: '立即付款' },
      { cancel: '取消订单', confirm: '立即付款' },
      { cancel: '退款/售后', confirm: '再次购买' },
    ],
    orderList: null,
    btnText: { cancel: '取消订单', confirm: '立即付款' },
    color: '#000',
    user_id: '',
    time: 30 * 60 * 60 * 1000,
    imageURL: 'https://img.yzcdn.cn/upload_files/2017/07/02/af5b9f44deaeb68000d7e4a711160c53.jpg'
  },
  onTabsChange (e) {
    this.setData({
      active: e.detail.index,
      // btnText: this.data._active[e.detail.index]
    })
    this.getOrders()
  },
  /**
   * 生命周期函数--监听页面加载
   */
  onLoad: function ({ type = 0 }) {
    var info = wx.getStorageSync('uinfo')
    // info.user.id = 203
    // wx.setStorageSync('uinfo', info)
    this.setData({
      user_id: info && info.user ? info.user.id : '',
      active: Number(type)
    })
    // if (type == 0) this.getOrders()
    // this.orderCancel()
  },
  async getOrders () {
    if (!this.data.user_id) {
      return
    }
    wx.showLoading({ mask: true })
    let active = this.data.active
    let { code, data } = await mode.getOrders({
      order_status: String(active == 0 ? '' : active - 1),
      user_id: this.data.user_id
    })
    setTimeout(() => {
      wx.hideLoading()
    }, 100)
    if (code && data) {
      // let status = [
      //   {
      //     text:'待发货',
      //     val:100
      //   },
      // ]
      data.forEach(v => {
        if (v.order_over_pay_time)
          v.theRemainingTime = new Date(v.order_over_pay_time.replace(/\-/g, '/')).getTime() - new Date().getTime()
        if (v.orders_type == 2) {
          ////订单状态 0待支付 1待发货 2待收货 3已收货 4已取消 5已删除 默认0
          v.order_status = [100, 200, 300, 400].findIndex(v2 => v2 == v.status) + 1
        }
        v.status_text = (v.status_text == '已完成' && !v.exchange_order) ? '交易完成' : v.status_text
      })
      this.setData({
        orderList: data || [],
      })
    }
  },
  async orderCancel () {
    let { code, data } = await mode.orderCancel()
    if (code) {
      this.setData({
        reasonList: data.map(v => v.reason)
      })
    }
  },
  buyAgain (e) {
    let goods = e.target.dataset.value
    if (goods.orders_type == 2) {
      let type = ['', 'integral_good_id', 'integral_coupon_id']
      app.goUrl(`/pages/goods-details/goods-details?id=${goods[type[goods.status_type]]}&type=${goods.status_type}`)
      return
    }
    if (!goods.order_goods) return
    let goods_info = goods.order_goods.map(v => {
      return {
        goods_id: v.goods_id,
        number: v.number
      }
    })
    app.goUrl(`/pages/settlement/settlement?goods_info=${JSON.stringify(goods_info)}`)
  },
  shopingNow () {
    app.goUrl('/pages/exclusive/exclusive', true)
  },
  jumpOrderDetails (e) {
    // console.log(e)
    let { id, orders_type } = e.currentTarget.dataset
    app.goUrl(`/pages/orderInfo/orderInfo?orders_type=${orders_type}&order_id=${id}`)
  },
  finished () {
    // console.log('订单已过期');
    // wx.showModal({
    //   title: '提示',
    //   content: '订单已过期!',
    //   showCancel:false,
    //   success: function (res) {
    //     app.backPage();
    //   }
    // })
  },
  orderPayBtn (e) {
    wx.showLoading()
    let { type, id, index, no, total, freight,remarks } = e.currentTarget.dataset
    let { user_id } = this.data
    type == 1 && wx.login({
      success: (res) => {
        mode.getOpenid(res.code).then(item => {
          mode.userOrderPay({
            openid: item.data,
            out_trade_no: no,
            totalPrice: total
          }).then(item => {
            this.orderPay(item,remarks)
          })
        })
      }
    })
    type == 2 && wx.$api.integralPay({ orders_id: id, user_id }).then(res => {
      this.orderPay(res)
    })
  },
  orderPay (item,remarks) {//支付
    // let out_trade_no
    wx.showLoading({ title: '支付中...' })
    wx.hideLoading()
    console.log('payyyyyy', item)
    var newObj = JSON.parse(item.data)
    wx.requestPayment({
      nonceStr: newObj.nonceStr,
      package: newObj.package,
      paySign: newObj.paySign,
      timeStamp: newObj.timeStamp,
      signType: 'MD5',
      success: (res) => {
        if(remarks&&remarks=="体验装订单"){
          wx.navigateTo({
            url: '/pages/orderInfo/orderInfo?isTest=1&ispay=1',
          })
        }else{
          wx.showToast({
            title: '支付成功',
            icon: 'success',
            duration: 1500
          })
          // this.getOrdersInfo(false)
          setTimeout(() => {
            this.getOrders()
          }, 1500)
        }
      },
      fail (res) {
        console.log(res)
        wx.showToast({
          title: '支付失败',
          icon: 'error',
          duration: 2000
        })
      }
    })

  },
  confirmOrder (e) {
    Dialog.confirm({
      zIndex: 999,
      closeOnClickOverlay: true,
      width: '280px',
      theme: '',
      title: '确认已收到货',
      message: '为了保障售后权益，请检查后再确认收货',
    })
      .then(async () => {
        wx.showLoading({
          title: '确认收货中...',
          mask: true,
        })
        let { code, data, msg } = await mode.confirmOrder({
          order_id: e.target.dataset.id,
          order_type: e.target.dataset.orders_type
        })
        wx.hideLoading()
        if (code == 1) {
          wx.showToast({ title: '确认收货成功!' })
          setTimeout(() => {
            this.getOrders(false)
          }, 1500)
        } else wx.showToast({ title: msg, icon: 'none' })
      })
      .catch(() => {
      })
    return
    wx.showModal({
      title: '确认已收到货',
      content: '为了保障售后权益，请检查后再确认收货',
      showCancel: true,
      cancelText: '取消',
      cancelColor: '#000000',
      confirmText: '确定',
      confirmColor: '#277CE3',
      success: async (result) => {
        if (result.confirm) {
          wx.showLoading({
            title: '确认收货中...',
            mask: true,
          })
          let { code, data, msg } = await mode.confirmOrder({
            order_id: e.target.dataset.id,
            order_type: e.target.dataset.orders_type
          })
          wx.hideLoading()
          if (code == 1) {
            wx.showToast({ title: '确认收货成功!' })
            setTimeout(() => {
              this.getOrders(false)
            }, 1500)
          } else wx.showToast({ title: msg, icon: 'none' })
        }
      },
      fail: () => { },
      complete: () => { }
    })
  },
  afterSales (e) {//去售后
    app.goUrl(`/pages/applyAfter/applyAfter?order_id=${e.target.dataset.id}`)
    // wx.redirectTo({
    //   url: `/pages/applyAfter/applyAfter?order_id=${e.target.dataset.id}`
    // })
  },
  changeAddress (e) {//修改订单地址
    let { id, ordertype, status } = e.currentTarget.dataset
    // app.goUrl(`/pages/address-save/address-save?type=3&orders_type=${orders_type}&order_id=${id}`)
    app.goUrl(`/pages/address/address?addressType=1&orderId=${id}&orderType=${ordertype}&integral=${status == 1 ? '1' : ''}`)
  },
  onChange (event) {
    console.log(event)
    this.setData({
      reasonForCancellation: event.detail.value
    })
  },
  async confirmCancel (e) {
    let { type, id } = e.currentTarget.dataset
    let { cancelId, reasonForCancellation } = this.data
    // return
    // if (!reasonForCancellation.trim()) return wx.showToast({ title: '请输入要取消订单的原因!', icon: 'none' })
    wx.showLoading()
    let { code, data, msg } = await mode.ordersCancel({
      order_id: id,
      cancel_order: this.data.reasonList.find((v, i) => i == e.detail.value),
      orders_type: type
    })
    wx.hideLoading()
    if (code == 1) {
      wx.showToast({
        title: '取消订单成功',
        duration: 1500,
        mask: true,
      })
      this.setData({ iscancel: false })
      setTimeout(() => {
        this.getOrders()
      }, 1500)
    } else wx.showToast({
      title: msg,
      icon: 'none',
      mask: true,
    })
  },
  onClose (e) {
    this.setData({ iscancel: e.detail != "cancel" })
  },
  ordersCancel (e) {//取消订单
    this.setData({
      iscancel: true,
      cancelId: e.target.dataset.id,
      reasonForCancellation: '',
    })

  },

  /**
   * 生命周期函数--监听页面初次渲染完成
   */
  onReady: function () {

  },

  /**
   * 生命周期函数--监听页面显示
   */
  onShow: function () {
    if (this.data.user_id) {
      this.getOrders()
      this.orderCancel()
    }
  },

  /**
   * 生命周期函数--监听页面隐藏
   */
  onHide: function () {

  },

  /**
   * 生命周期函数--监听页面卸载
   */
  onUnload: function () {

  },

  /**
   * 页面相关事件处理函数--监听用户下拉动作
   */
  async onPullDownRefresh () {
    //在当前页面显示导航条加载动画
    wx.showNavigationBarLoading()
    await this.getOrders()
    //隐藏导航条加载动画
    wx.hideNavigationBarLoading()
    //停止下拉刷新
    wx.stopPullDownRefresh()
    wx.showToast({ title: '刷新成功!', icon: 'none' })
  },

  /**
   * 页面上拉触底事件的处理函数
   */
  onReachBottom: function () {

  },
  /**
   * 
   */
  toAfterSale () {
    wx.navigateTo({
      url: '../../components/AfterSales/AfterSales',
    })
  }
})